import {defineStore} from "pinia";
import {messageStore} from "~/store/messageStore";

export const webSocketStore = defineStore('webSocketStore', ()=>{
    const ws:Ref<MyWebSocket|null>=ref(null)
    const url=useRuntimeConfig().public.webSocketURL
    function msgCallback(e:MessageEvent) {
        const ms=messageStore()
        ms.addMsg(e.data)
        showToast({
            message:'您有一条新的消息',
            duration:2500,
        })
        // console.log(e.data)
    }
    const initWS=()=>{
        ws.value=new MyWebSocket(url,userStore().getToken(),msgCallback)
    }
    const getWS = ():MyWebSocket|null=>{
        if(ws.value) return ws.value
        initWS()
        return ws.value
    }
    return {ws,getWS,initWS}
})

